<?php

namespace CloudFlare;


use think\Log;

class CloudFlareApi
{
//    private $accountId = "4b6a947108959b3c03a2772b07b92ae2";
//    private $appkey = "69a52087dfb80440fe87c7f5aa5155978c3cd";
//    private $appToken = "IsdQn25la5I1SX5s5jdxT0tbYjljkUGyP6zT746a";
//    private $email = "service@unionblue.cn";

    private $accountId = "0be9529b9d240696d18111458329461d";
    private $appkey = "2813f16c022d48b53ce50e4a14fde64df93e7";
    private $appToken = "FeUQFBUCdrkXrG0r-vg8VB2M1rYjgHxLdTVKgXrwc";
    private $email = "dgwin147258@gmail.com";

    /**
     * CloudFlareApi constructor.
     */
    function __construct()
    {
    }

    /**
     * 获取API接口URL根地址
     *
     * @return string
     */
    public function getApiUrl($path)
    {
        $url = "https://api.cloudflare.com" . CloudFlareApiConstent::PREFIX . $path;

        // 替换path中的{account_id}为$this->>appkey
        $url = str_replace('{account_id}', $this->accountId, $url);
        return $url;
    }

    /**
     * 发送请求
     * @param $apiPath
     * @param array $params
     * @param string $requestType
     * @param string $headers
     * @return mixed
     */
    public function request($apiPath, $params = [], $requestType = 'POST', $headers = '')
    {
        $url = $this->getApiUrl($apiPath);

        Log::info('CloudFlareApi request,url:' . $url . ',params:' . json_encode($params));

        $timeout = 30;
        $params_encode = json_encode($params);

        //根据请求类型设置特定参数
        $opts = array(
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
        );
        if ($headers != "") {
            $opts[CURLOPT_HTTPHEADER] = $headers;
        } else {
            $opts[CURLOPT_HTTPHEADER] = [
                'Content-type: application/json',
                'X-Auth-Email: ' . $this->email,
                'X-Auth-Key: ' . $this->appkey,
                'Authorization: Bearer ' . $this->appToken,
            ];
        }
        switch (strtoupper($requestType)) {
            case "GET" :
                $opts[CURLOPT_HTTPGET] = true;
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                $opts[CURLOPT_ENCODING] = '';
                $opts[CURLOPT_CUSTOMREQUEST] = 'GET';
                break;
            case "POST":
                $opts[CURLOPT_POST] = true;
                $opts[CURLOPT_CUSTOMREQUEST] = "POST";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            case "PUT" :
                $opts[CURLOPT_CUSTOMREQUEST] = "PUT";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            case "DELETE":
                $opts[CURLOPT_CUSTOMREQUEST] = "DELETE";
                $opts[CURLOPT_POSTFIELDS] = $params_encode;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);

        $result = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if (!empty($err)) {
            Log::error('cloudflare api request:' . json_encode($result) . ',error:' . json_encode($err));
        }
        return json_decode($result, true);
    }

    /**
     * post请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function post($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'POST', $headers);
    }


    /**
     * get请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function get($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'GET', $headers);
    }

    /**
     * put请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function put($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'PUT', $headers);
    }

    /**
     * delete请求
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function delete($apiPath, $params = [], $headers = '')
    {
        return $this->request($apiPath, $params, 'DELETE', $headers);
    }

    /**
     * 发送文件
     * @param $apiPath
     * @param array $params
     * @param string $headers
     * @return mixed
     */
    public function postFile($url, $params = [], $headers = '')
    {
        Log::info('CloudFlareApi postFile,url:' . $url . ',params:' . json_encode($params));

        $timeout = 0;

        //根据请求类型设置特定参数
        $opts = array(
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
        );
        if ($headers != "") {
            $opts[CURLOPT_HTTPHEADER] = $headers;
        } else {
            $opts[CURLOPT_HTTPHEADER] = [
                'X-Auth-Email: ' . $this->email,
                'X-Auth-Key: ' . $this->appkey,
                'Authorization: Bearer ' . $this->appToken,
            ];
        }
        $opts[CURLOPT_POST] = true;
        $opts[CURLOPT_CUSTOMREQUEST] = "POST";
        $opts[CURLOPT_POSTFIELDS] = $params;

        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);

        $result = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if (!empty($err)) {
            Log::error('cloudflare api request:' . json_encode($result) . ',error:' . json_encode($err));
        }
        return $result;
    }
}
